﻿myApp.controller("ListingEntryController", function ($scope, $http, $routeParams, $location, $window, $sce, authService) {
    $scope.form = {};
    $scope.uploadedImages = [];
    $scope.locationDropdown = {};
    $scope.stateDropdown = {};
    $scope.property = {};
    $scope.isopen = true;
    //$scope.propertyUrl = $sce.trustAsResourceUrl('http://lskweb.dlinkddns.com/propertyentryweb.aspx');

    $scope.propertyUrl = $sce.trustAsResourceUrl('http://lskweb.dlinkddns.com/propertyentryweb.aspx?id=' + $routeParams.id + '&userId=' + $scope.authentication.userType + '&ListType=' + $scope.property.ListType);

    //$scope.propertyUrl = $sce.trustAsResourceUrl('http://localhost/REM/propertyentryweb.aspx');
    //var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    //var eventer = window[eventMethod];
    //var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

    //// Listen to message from child window
    //eventer(messageEvent, function (e) {
    // //   console.log('parent received message!:  ', e.data);
    //}, false);


    function pageInit() {
       // $scope.loader.loading = true;
        console.log($scope.property);

        // TODO : Getting the authentication user objec, I already get it at the page controller and save in local storage
        // another way to get the data is : authService.authentication, refer PageController, inject the service
        console.log("User Info");
        $scope.authentication = authService.authentication;
        //alert(JSON.stringify(authService.authentication));
        if ($scope.authentication.isAuth === false) $location.path('/Login');
        if ($scope.authentication.userType == "Valid User") $location.path('/#');
        if ($scope.authentication.userName.indexOf('@') !== -1) {
            console.log("@ found");
            $location.path('/#');
        }


        $http.get('api/Property/GetState')
        .success(function (data) {
            $scope.states = data;
        }
        )

        $http.get('api/Property/GetPropertyType')
           .success(function (data) {
               $scope.propertyTypes = data;
           }
           )

        if ($routeParams.id) {


            var url = 'api/Property/GetProperty/' + $routeParams.id;
            $http.get(url).success(function (data) {
                $scope.property = data.property;
                $scope.stateDropdown = data.stateList;
                $scope.locations = data.locationList;
                $scope.roadNames = data.roadList;
                $scope.projects = data.projectList;
                $scope.states = data.stateList;
                $scope.property.ListType = $scope.property.ListType ? $scope.property.ListType.toString() : "";
                $scope.propertyUrl = $sce.trustAsResourceUrl('http://lskweb.dlinkddns.com/propertyentryweb.aspx?id=' + $routeParams.id + '&userId=' + $scope.authentication.userType + '&ListType=' + $scope.property.ListType);
                //  $scope.propertyUrl = $sce.trustAsResourceUrl('http://localhost/REM/propertyentryweb.aspx?id=' + $routeParams.id + '&userId=' + $scope.authentication.userType + '&ListType=' + $scope.property.ListType);
                if (data.pictureList) {
                    angular.forEach(data.pictureList, function (object) {
                        $scope.uploadedImages.push({ uploadedImgSrc: object.pictureURL, PhotoId: object.PictureDesc });
                    })
                }
              //  $scope.loader.loading = false;

            })
        }
       // $scope.loader.loading = false;


    }


    $scope.single = function (image) {
      //  $scope.loader.loading = true;
        var formData = new FormData();
        console.log(image);
        //formData.append('image', image.file);
        formData.append('image', image.dataURL);
        formData.append('property', angular.toJson($scope.property));
        $http.post('api/Property/upload', formData, {
            headers: { 'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function (result) {
            $scope.clear();
            $scope.uploadedImages.push({ uploadedImgSrc: result.OriginalUrl, PhotoId: result.PhotoId });
          //  $scope.loader.loading = false;

        });
    }

    $scope.changeState = function () {
        if ($scope.property.StateId) {
            $http.get('api/Property/GetLocation/' + $scope.property.StateId)
           .success(function (data) {

               $scope.locations = data;
           }
           )
        }
    }

    $scope.changeLocation = function () {
        if ($scope.property.LocationId) {
            $http.get('api/Property/GetRoadName/' + $scope.property.LocationId)
           .success(function (data) {
               $scope.roadNames = data;
           }
           )
        }
    }

    $scope.changeRoadName = function () {
        if ($scope.property.RoadId) {
            $http.get('api/Property/GetProject/' + $scope.property.RoadId)
           .success(function (data) {
               $scope.projects = data;
           }
           )
        }
    }

    $scope.close = function () {

        $scope.warning = null;
        $scope.error = null;
        $scope.info = null;
    }

    $scope.clear = function (image) {
        angular.element("input[type='file']").val(null);
        imaage = null;
        $scope.image = null;
        $scope.data.image = null;
        $scope.form.uploadPhoto.$setPristine();

        //  $scope.$apply();
    }

    $scope.deleteImage = function (image) {

      //  $scope.loader.loading = true;
        $http.post('api/Property/DeletePhoto', image.PhotoId)
        .success(function (result) {
            var index = $scope.uploadedImages.map(function (e) { return e.PhotoId; }).indexOf(image.PhotoId)
            $scope.uploadedImages.splice(index, 1);
        //    $scope.loader.loading = false;
        })
        console.log(image);
    }

    function validation() {
        $scope.warning = [];

        if (!$scope.property.RoadId)
            $scope.warning.push({ msg: "Road must not be empty!" });
        if (!$scope.property.StateId)
            $scope.warning.push({ msg: "State must not be empty!" });
        if (!$scope.property.ProjectId)
            $scope.warning.push({ msg: "Project must not be empty!" });
        if (!$scope.property.ListType)
            $scope.warning.push({ msg: "List Type must not be empty!" });
        if (!$scope.property.LocationId)
            $scope.warning.push({ msg: "Location must not be empty!" });
        if (!$scope.property.PropertyTypeId)
            $scope.warning.push({ msg: "Property Type must not be empty!" });
        if (!$scope.property.UnitNumber)
            $scope.warning.push({ msg: "Unit Number must not be empty!" });
        //if ($scope.property.UnitNumber && isNaN($scope.property.UnitNumber))
        //    $scope.warning.push({ msg: "Unit Number must not be empty!" });
        if (!$scope.property.BUWidth)
            $scope.warning.push({ msg: "BUWidth must be an integer!" });
        if (!$scope.property.BULength)
            $scope.warning.push({ msg: "BULength must be an integer!" });
        if (!$scope.property.SRYes && !$scope.property.SCYes && !$scope.property.SLYes
            && !$scope.property.SIYes && ($scope.property.ListType == 1 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Sale and make sure the price is greter than 0" });
        if (!$scope.property.RRYes && !$scope.property.RCYes && !$scope.property.RLYes
            && !$scope.property.RRYes && ($scope.property.ListType == 2 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Rent and make sure the price is greter than 0" });
        if (!$scope.property.SRAmt && !$scope.property.SCAmt && !$scope.property.SLAmt
            && !$scope.property.SIAmt && ($scope.property.ListType == 1 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Sale and make sure the price is greter than 0" });
        if (!$scope.property.RRAmt && !$scope.property.RCAmt && !$scope.property.RLAmt
            && !$scope.property.RIAmt && ($scope.property.ListType == 2 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Rent and make sure the price is greter than 0" });
        if ($scope.property.SRAmt <= 0 && $scope.property.SCAmt <= 0 && $scope.property.SLAmt <= 0
            && $scope.property.SIAmt <= 0 && ($scope.property.ListType == 1 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Sale and make sure the price is greter than 0" });
        if ($scope.property.RRAmt <= 0 && $scope.property.RCAmt <= 0 && $scope.property.RLAmt <= 0
            && $scope.property.RIAmt <= 0 && ($scope.property.ListType == 2 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Rent and make sure the price is greter than 0" });
        if ($scope.warning.length > 0)
            return false;
        else {
            // Insert the slister and rlisterid
            if ($scope.property.ListType == 1 || $scope.property.ListType == 3) $scope.property.SListerId = $scope.authentication.userType;
            if ($scope.property.ListType == 2 || $scope.property.ListType == 3) $scope.property.SListerId = $scope.authentication.userType;
            $scope.warning = null;
            return true;
        }
    }

    $scope.clearEntry = function () {
        $location.path("/ListingEntry/");
    }

    $scope.save = function () {
        if (!validation()) {
            window.scrollBy(0, -10000);
            return;
        }

        $scope.property.BUSF = $scope.property.BUWidth * $scope.property.BULength;

        $http.post('api/Property/save', $scope.property)
            .success(function (result) {
                $scope.property.PropertyId = result.Message;
                $scope.property = result.property;
                $scope.property.ListType = $scope.property.ListType.toString();

                $scope.info = "Save successful";
                // if is first time created, reload
                if (!$location.path().split("/")[2])
                    $location.path("/ListingEntry/" + $scope.property.PropertyId);
            })
    }

    $scope.close = function () {
        $scope.warning = null;
        $scope.info = null;
        $scope.error = null;
    }

    pageInit();
});